/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller.project;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.Project;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IProjectService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hhl
 * @version $Id: ProjectController.java, v 0.1 2018年10月23日 下午4:56:53 hhl Exp $
 */
@Controller
@RequestMapping(value = "project")
public class ProjectController {
    protected static final LoggerAdapter LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);
    @Autowired
    private IProjectService              projectService;

    @Autowired
    private ICommonService               commonService;

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        try {
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
            return "project/projectList";
        } catch (Exception e) {
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /*
     * @RequestMapping(value = "List") public String index(ModelMap model, HttpServletRequest request,
     * 
     * @RequestParam(value = "pageSize", required = false) String pageSize,
     * 
     * @RequestParam(value = "currentPage", required = false) String currentPage, Project data) { User
     * user = (User) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER); try { Page page =
     * new Page(); page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
     * page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
     * BaseController.setSortByColumn(request, "project_name", "asc"); data.setOrderField((String)
     * request.getAttribute("orderField")); data.setOrderFlag((String)
     * request.getAttribute("orderFlag")); PaginationBean<Project> paginationBean =
     * projectService.queryPageList(data, page); model.addAttribute("list",
     * paginationBean.getPageList()); model.addAttribute("listPage", paginationBean);
     * request.setAttribute("msg", BaseController.getParameter("msg"));
     * BaseController.removeParameter("msg");
     * 
     * model.addAttribute("currentPage", currentPage == null ? 0 : Integer.valueOf(currentPage));
     * model.addAttribute("user", user); model.addAttribute("data", data); return
     * "project/projectList"; } catch (Exception e) { LOGGER.error(e.getMessage(), e); return "error";
     * }
     * 
     * }
     */

    @RequestMapping(value = "/List")
    @ResponseBody
    public ResponseResult List(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "rows", required = false) String pageSize,
                               @RequestParam(value = "page", required = false) String currentPage,
                               Project data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            /*
             * if (userEmployee.getUserid().equals("admin")) { Page page = new Page();
             * page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
             * page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
             * BaseController.setSortByColumn(request, "project_name", "asc"); data.setOrderField((String)
             * request.getAttribute("orderField")); data.setOrderFlag((String)
             * request.getAttribute("orderFlag")); PaginationBean<Project> paginationBean =
             * projectService.queryPageList(data, page);
             * 
             * ResponseResult result = new ResponseResult();
             * result.setTotal(paginationBean.getTotalRecords());
             * result.setRows(paginationBean.getPageList()); return result;
             * 
             * } else {
             */
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "project_name", "asc");

            if (request.getAttribute("orderField").equals("projectName")) {
                data.setOrderField("p.project_name");
            } else if (request.getAttribute("orderField").equals("completeDate")) {
                data.setOrderField("p.complete_date");
            } else if (request.getAttribute("orderField").equals("addDate")) {
                data.setOrderField("p.add_date");
            } else if (request.getAttribute("orderField").equals("cz")) {
                data.setOrderField("p.project_name");
            } else {
                data.setOrderField((String) request.getAttribute("orderField"));
            }
            /* data.setOrderField((String) request.getAttribute("orderField")); */
            data.setOrderFlag((String) request.getAttribute("orderFlag"));

            data.setPrincipal(
                userEmployee.getEmid() == null ? null : String.valueOf(userEmployee.getEmid()));
            data.setAddUid(userEmployee.getUid() == null ? null : userEmployee.getUid());
            PaginationBean<Project> paginationBean = projectService.queryPageList(data, page);

            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<Project>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());

            return result;
            /*
             * }
             */
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /*
             * if (userEmployee.getEmid() != null) { Integer emid[] = { userEmployee.getEmid() };
             * employee.setEmpids(emid); }
             */
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);

            model.addAttribute("List", List);
            return "project/addProject";
        } catch (Exception e) {
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }

    }

    @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /*
             * if (userEmployee.getEmid() != null) { Integer emid[] = { userEmployee.getEmid() };
             * employee.setEmpids(emid); }
             */
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);
            model.addAttribute("List", List);
            Project data = new Project();
            data.setId(id);
            data = projectService.queryByPK(data);
            model.addAttribute("data", data);

            return "project/updateProject";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "uui", required = false) String uui) {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            Employee employee = new Employee();
            /*
             * if (userEmployee.getEmid() != null) { Integer emid[] = { userEmployee.getEmid() };
             * employee.setEmpids(emid); }
             */
            java.util.List<Employee> List = commonService.queryNotCurrByAllEmployee(employee);
            model.addAttribute("List", List);
            Project data = new Project();
            data.setId(id);
            data.setProjectUui(uui);
            data = projectService.queryByPK(data);
            model.addAttribute("data", data);

            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");

            return "project/detailsProject";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "项目信息", moduleName = "项目管理", method = "新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(ModelMap model, HttpServletRequest request, Project data) {
        try {
            /*
             * String type = (String) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE); if
             * (type.equals("2")) {
             */
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setAddDate(new Date());
            data.setProjectLevel(0);
            /* data.setAddUid(userEmployee.getEmid()); */
            data.setAddUid(userEmployee.getUid());
            String uui = projectService.add(data);
            BaseController.setParameter("msg", "保存成功");
            /* } */
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加项目信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "项目信息", moduleName = "项目管理", method = "新增")
    @RequestMapping(value = "/addSaveContinue", method = RequestMethod.POST)
    public String addSaveContinue(ModelMap model, HttpServletRequest request, Project data) {
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setAddDate(new Date());
            /* data.setAddUid(userEmployee.getEmid()); */
            data.setAddUid(userEmployee.getUid());
            data.setProjectLevel(0);
            projectService.add(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:addInInt";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加项目信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "项目信息", moduleName = "项目管理", method = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            for (String id : idList) {
                Project data = new Project();
                data.setId(Integer.valueOf(id));
                projectService.delete(data);
            }
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "项目信息", moduleName = "项目管理", method = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(ModelMap model, HttpServletRequest request, Project data) {
        try {
            projectService.update(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:index";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/validation")
    public @ResponseBody Map<String, Object> validation(@RequestParam(value = "projectName") String projectName,
                                                        @RequestParam(value = "id") String id,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            Project data = new Project();
            data.setId(id.equals("null") || id.equals("") ? null : Integer.valueOf(id));
            data.setProjectName(projectName.trim());
            int count = projectService.validation(data);
            if (count == -99) {
                dataMap.put("msg", -99);
            } else if (count == 0) {
                dataMap.put("msg", 0);
            } else {
                dataMap.put("msg", -1);
            }

        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("msgg", -99);
        }
        return dataMap;
    }

}
